// electron打包用的插件
import type { Plugin } from 'vite'
import esbuild from 'esbuild'
import fs from 'node:fs'
import * as electronBuild from 'electron-builder'
import path from 'path'

// electron 不认识ts文件  要编译成js文件
const buildElectron = () => {
  esbuild.buildSync({
    entryPoints: ['src/background.ts'],
    bundle: true,
    outfile: 'dist/background.js',
    platform: 'node',
    target: 'node12',
    external: ['electron']
  })
}

// 打包  需要先等vite打完包之后就有index.html 再执行electron-builder打包
// 因此使用closeBundle钩子就非常合适
export const ElectronBuildPlugin = (): Plugin => {
  return {
    name: 'ElectronBuildPlugin',
    closeBundle() {
      buildElectron()

      // electron-builder需要指定package.json的main属性
      const json = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
      json.main = 'background.js'

      fs.writeSync(fs.openSync('dist/package.json', 'w'), JSON.stringify(json, null, 2))

      //解决electron-builder的大bug：  它会给你下载垃圾文件，而且还下载不下来
      fs.mkdirSync(path.join(process.cwd(), 'dist/node_modules'))

      // 设置electron-builder的打包项
      electronBuild.build({
        config: {
          directories: {
            output: path.resolve(process.cwd(), 'release'), //输出目录
            app: path.resolve(process.cwd(), 'dist') //app目录
          },
          asar: true,
          appId: 'com.test.app',
          productName: 'vite-electron',
          nsis: {
            oneClick: false, // 取消一键安装
            allowToChangeInstallationDirectory: true // 允许用户选择安装目录
          }
        }
      })
    }
  }
}
